package org.openkanban.client.ui.adminpanel;

import org.openkanban.client.ui.presenter.LogInRequestCallback;
import org.openkanban.client.ui.presenter.PreparedRequest;
import org.openkanban.client.util.Md5Utils;

import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.VerticalAlignment;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.FormItem;
import com.smartgwt.client.widgets.form.fields.PasswordItem;
import com.smartgwt.client.widgets.form.fields.StaticTextItem;
import com.smartgwt.client.widgets.form.fields.TextItem;

/**
 * GUI Element for the LoginForm
 */
public class LoginForm extends DynamicForm {

    private StaticTextItem message;

    private PasswordItem password;
    private TextItem email;

    public LoginForm() {
	setStyleName("login-form");

	email = new TextItem();
	email.setName("email");
	email.setTitle("Email");
	email.setRequired(true);

	password = new PasswordItem();
	password.setName("password");
	password.setTitle("Password");
	password.setRequired(true);

	message = new StaticTextItem();
	message.setValue("email or password invalid!");
	message.setTitle("Error:");
	message.setTextAlign(Alignment.LEFT);
	message.setColSpan(2);
	message.setTextBoxStyle("failedMessage");
	message.setVisible(false);

	// form
	setHeight100();
	setWidth100();
	setPadding(3);
	setColWidths("60%", "40%");
	setLayoutAlign(VerticalAlignment.BOTTOM);
	setFields(new FormItem[] { email, password, message });
    }

    @Override
    public void submit() {
	if (validate()) {
	    String md5Password = Md5Utils.md5(password.getValueAsString());
	    PreparedRequest preparedRequest = new PreparedRequest("user", "login", "email", email.getValueAsString(), "password",
		    md5Password);
	    preparedRequest.sendAsyncRequest(new LogInRequestCallback());
	}
    }

    public StaticTextItem getMessage() {
	return message;
    }

}
